import { doApplicationEdit, fetchApplicationInfo } from "@/services/robotManagement";
import jsonDataUtils from "@/utils/jsonDataUtils";
import { Form, Tag, Input, Radio, Button, message, Tooltip, Icon, InputNumber, Switch, Select, Cascader, DatePicker } from "antd";
import React from "react";
import ChannelInfoEdit from "./channelInfoEdit";
import ChannelSetting from "./ChannelSetting";
import UserSession from "@/UserSession";
import { businessTypeList, chargingAndDetail } from "@/services/chargingManage";
import BusinessReadonly from "../ChargingManage/businessManage/businessReadonly";
import moment from "moment";
import { formatMessage } from 'umi-plugin-react/locale';

class BasicSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      applicationInfo: {},
      businessList: [],
      caseOptions: [],
      packageId: ""
    }
  }

  componentDidMount() {
    this.getApplicationInfo()
    this.getBusinessList()
  }

  getBusinessList = async () => {
    const res = await businessTypeList()
    res.settlement = res.settlement.sort((a, b) => b.id - a.id)
    this.setState({ businessList: res.settlement })
  }

  changeBusiness = value => {
    this.props.form.resetFields(["planDetailId"])
    this.getCaseOptions(value)
    this.BusinessReadonly.initModal(value)
  }

  getCaseOptions = async id => {
    const res = await chargingAndDetail({ id })
    this.setState({ caseOptions: res })
  }

  changeDetailId = (value, selectedOptions) => {
    if (selectedOptions && selectedOptions[1]) {
      this.setState({ packageId: selectedOptions[1].packageId })
    }
  }

  openInfoModal = (infoData) => {
    this.ChannelInfoEdit.openModal(infoData);
  }

  refreshByOk = () => {
    const { channel } = this.props;
    this.getApplicationInfo();
  }

  getApplicationInfo = async () => {
    const { applicationId, channel } = this.props;
    const res = await fetchApplicationInfo({ id: applicationId })
    const planDetail = res.planDetail ? res.planDetail : {}
    this.setState({ applicationInfo: res, packageId: planDetail.packageId }, () => {
      this.props.form.setFieldsValue({
        planDetailId: res.planDetailId,
        startTime: res.startTime ? moment(res.startTime) : null,
        endTime: res.endTime ? moment(res.endTime) : null,
        enterpriseId: res.enterpriseId
      });
      this.getCaseOptions(res.enterpriseId)
      this.BusinessReadonly.initModal(res.enterpriseId)
    })
  }

  doSaveApplicationInfo = () => {
    const that = this;
    that.props.form.validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        const { applicationInfo } = that.state;
        const { channel } = that.props;
        let digitalPerson = values.digitalPerson == 0 ? true : false;
        values.startTime = values.startTime ? moment(values.startTime).format("YYYY-MM-DD") : ''
        values.endTime = values.endTime ? moment(values.endTime).format("YYYY-MM-DD") : ''
        let obj = { ...applicationInfo, digitalPerson, ...values };
        if (digitalPerson) {
          obj.digitalPersonCode = "digitMan_01"
        };
        if (channel == 'QWX_NATIVE') {
          let platformParams = applicationInfo.platformParams && jsonDataUtils.isJsonString(applicationInfo.platformParams) ? JSON.parse(applicationInfo.platformParams) : {};
          platformParams.receiveToken = values.receiveToken;
          platformParams.receiveEncodingAesKey = values.receiveEncodingAesKey;
          obj.platformParams = JSON.stringify(platformParams);
        };
        if (channel === 'DIGITAL_SCREEN') {
          obj.isPassword = values.isPassword
          if (obj.isPassword) {
            obj.password = values.password
          }
        };
        let res = await doApplicationEdit(obj)
        message.info(res.message);
        that.getApplicationInfo();
      }
    });
  }

  doCopy = type => {
    let text = '';
    switch (type) {
      case 'receiveMessageUrl':
        text = document.getElementById('receiveMessageUrl');
        break;
    };
    if (document.body.createTextRange) {
      var range = document.body.createTextRange();
      range.moveToElementText(text);
      range.select();
    } else if (window.getSelection) {
      let selection = window.getSelection();
      let range = document.createRange();
      range.selectNodeContents(text);
      selection.removeAllRanges();
      selection.addRange(range);
    };
    document.execCommand('Copy');
    message.success(formatMessage({ id: 'common.copySuccess' }));
  };

  disabledendTime = endValue => {
    const startValue = this.props.form.getFieldValue("startTime")

    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  };

  render() {
    const { getFieldDecorator, getFieldValue, resetFields } = this.props.form
    const { robotId, channel, applicationId } = this.props
    const { applicationInfo, businessList, caseOptions } = this.state;
    const layout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 20 },
    };
    const layoutButton = {
      wrapperCol: { span: 20, offset: 3 },
    };

    return (
      <div>
        <Form {...layout}>
          <Form.Item label={formatMessage({ id: 'basicSetting.selectEnterprise' })}>
            {getFieldDecorator("enterpriseId", { rules: [{ required: true, message:formatMessage({ id: 'basicSetting.selectEnterpriseRequired' }) }] })(
              <Select
                showSearch
                onChange={this.changeBusiness}
                optionFilterProp="children"
              >
                {businessList.map(item =>
                  <Select.Option value={item.id} key={item.id}>
                    {item.name}
                  </Select.Option>
                )}
              </Select>
            )}
          </Form.Item>
           <Form.Item label={formatMessage({ id: 'basicSetting.chargePlanDetail' })}>
            {getFieldDecorator("planDetailId", { rules: [{ required: true, message:formatMessage({ id: 'basicSetting.chargePlanDetailRequired' }) }] })(
              <Cascader options={caseOptions} fieldNames={{ label: 'name', value: 'id', children: 'children' }} onChange={this.changeDetailId} />
            )}
          </Form.Item>
          <Form.Item label={formatMessage({ id: 'basicSetting.accountStartDate' })}>
            {getFieldDecorator("startTime", { rules: [{ required: true, message:formatMessage({ id: 'basicSetting.accountStartDateRequired' }) }] })(
              <DatePicker onChange={() => resetFields(["endTime"])} />
            )}
          </Form.Item>
           <Form.Item label={formatMessage({ id: 'basicSetting.accountEndDate' })}>
            {getFieldDecorator("endTime", { rules: [{ required: true, message:formatMessage({ id: 'basicSetting.accountEndDateRequired' }) }] })(
              <DatePicker disabled={!getFieldValue("startTime")} disabledDate={this.disabledendTime} />
            )}
          </Form.Item>
          {
            channel === 'DIGITAL_SCREEN' ? (
                <Form.Item label={formatMessage({ id: 'basicSetting.controlPassword' })}>
                {getFieldDecorator("isPassword", { rules: [{ required: true, message: formatMessage({ id: 'basicSetting.selectRobotType' }) }] })(
                  <Radio.Group >
                    <Radio value={false}>{formatMessage({ id: 'basicSetting.openAccess' })}</Radio>
                    <Radio value={true}>{formatMessage({ id: 'basicSetting.encryptedAccess' })}</Radio>
                  </Radio.Group>
                )}
                {getFieldValue('isPassword') ? (
                  <Form.Item>
                    {getFieldDecorator("password", { rules: [{ required: true, message: formatMessage({ id: 'basicSetting.fillPassword' }) }] })(<Input maxLength={20} placeholder={formatMessage({ id: 'basicSetting.fillPassword' })} />)}
                  </Form.Item>
                ) : ''}
              </Form.Item>
            ) : ''
          }
          {
            channel == 'QWX_NATIVE' ? (
              <div>
                <Form.Item
                  label={
                     <span>
                      {formatMessage({ id: 'basicSetting.receiveMessageUrl' })}&nbsp;
                      <Tooltip title={formatMessage({ id: 'basicSetting.receiveMessageUrlTip' })}>
                        <Icon type='question-circle-o' />
                      </Tooltip>
                    </span>
                  }
                >
                  {getFieldDecorator("receiveMessageUrl")(<Input.TextArea autoSize disabled style={{ width: "80%" }} id="receiveMessageUrl" />)}
                  <Button size='small' onClick={() => this.doCopy("receiveMessageUrl")} style={{ marginLeft: 10 }}>{formatMessage({ id: 'common.copy' })}</Button>
                </Form.Item>
                <Form.Item
                  label={
                     <span>
                      {formatMessage({ id: 'basicSetting.token' })}&nbsp;
                      <Tooltip title={formatMessage({ id: 'basicSetting.tokenTip' })}>
                        <Icon type='question-circle-o' />
                      </Tooltip>
                    </span>
                  }
                >
               {getFieldDecorator("receiveToken")(<Input placeholder={formatMessage({ id: 'basicSetting.inputToken' })} style={{ width: "80%" }} />)}
                </Form.Item>
                <Form.Item
                  label={
                   <span>
                      {formatMessage({ id: 'basicSetting.encodingAesKey' })}&nbsp;
                      <Tooltip title={formatMessage({ id: 'basicSetting.encodingAesKeyTip' })}>
                        <Icon type='question-circle-o' />
                      </Tooltip>
                    </span>
                  }
                >
                  {getFieldDecorator("receiveEncodingAesKey")(<Input placeholder={formatMessage({ id: 'basicSetting.inputToken' })} style={{ width: "80%" }} />)}                </Form.Item>
              </div>
            ) : null
          }
          {
            channel == 'DD_NATIVE' ? (
              <Form.Item
                label={
                   <span>
                    {formatMessage({ id: 'basicSetting.receiveMessageUrl' })}&nbsp;
                    <Tooltip title={formatMessage({ id: 'basicSetting.receiveMessageUrlTip' })}>
                      <Icon type='question-circle-o' />
                    </Tooltip>
                  </span>
                }
              >
                {getFieldDecorator("receiveMessageUrl")(<Input.TextArea autoSize disabled style={{ width: "80%" }} id="receiveMessageUrl" />)}
                <Button size='small' onClick={() => this.doCopy("receiveMessageUrl")} style={{ marginLeft: 10 }}>{formatMessage({ id: 'common.copy' })}</Button>
              </Form.Item>
            ) : null
          }
          {
            channel == 'FS_NATIVE' ? (
              <Form.Item
                label={
                   <span>
                    {formatMessage({ id: 'basicSetting.receiveMessageUrl' })}&nbsp;
                    <Tooltip title={formatMessage({ id: 'basicSetting.receiveMessageUrlTip' })}>
                      <Icon type='question-circle-o' />
                    </Tooltip>
                  </span>
                }
              >
                {getFieldDecorator("receiveMessageUrl")(<Input.TextArea autoSize disabled style={{ width: "80%" }} id="receiveMessageUrl" />)}
                <Button size='small' onClick={() => this.doCopy("receiveMessageUrl")} style={{ marginLeft: 10 }}>{formatMessage({ id: 'common.copy' })}</Button>
              </Form.Item>
            ) : null
          }
          <Form.Item colon={false} label={<Button type="primary" onClick={this.doSaveApplicationInfo}>{formatMessage({ id: 'common.save' })}</Button>}></Form.Item>
          <BusinessReadonly onRef={ref => this.BusinessReadonly = ref} />


        </Form>
      </div>
    )
  }
}

export default Form.create()(BasicSetting)